<template>
  <el-dialog
    v-if="load"
    :title="title"
    v-model="visible"
    align-center
    width="850px"
    @close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      label-align="right"
      label-width="110"
      label-position="top"
    >
      <el-row :gutter="21">
        <el-col :span="10">
          <el-form-item label="平台站点" required>
            <VGroup class="w-full">
              <SelectPlatformSite
                v-model:platform="form.platform_id"
                v-model:site="form.site_code"
                @changePlatform="changePlatform($event, index)"
                @changeSiteInfo="changeSite($event, index)"
              >
              </SelectPlatformSite>
            </VGroup>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="国家" required>
            <SelectCountryCurrency
              ref="countryCurrencyRef"
              class="w-full"
              v-model="form.site_country_code"
              valueKey="country"
              placeholder="国家"
              @change="changeCountryCurrency"
            ></SelectCountryCurrency>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="推荐销售价" label-width="0">
            <el-input v-model.trim="form.sales_price" placeholder="请输入" clearable>
              <template #append>
                <select-currency
                  class="w-24"
                  v-model="form.currency_id"
                  placeholder="币种"
                  @change="changeCurrency"
                ></select-currency>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="竞品参考链接">
            <el-input v-model.trim="form.competitor_link" placeholder="请输入" clearable>
              <template #append>
                <el-button
                  style="background-color: #3487ff; color: #ffffff"
                  type="primary"
                  disabled
                  v-if="!form.competitor_link"
                  >跳转</el-button
                >
                <el-button
                  style="background-color: #3487ff; color: #ffffff"
                  type="primary"
                  v-else
                  ><a :href="form.competitor_link" target="_Blank">跳转</a></el-button
                >
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="头程推荐渠道">
            <div class="flex w-full">
              <el-select
                class="!w-[140px] radius-right-0"
                v-model="form.header_channel_id"
                clearable
                placeholder="请选择运输方式"
                @change="changeHead"
              >
                <el-option
                  v-for="item in channel_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <SelectChannel
                v-model="form.header_logistic_channel_id"
                placeholder="请选择物流渠道"
                type="head"
                :transportType="form.header_channel_id"
                @change="changeChannel($event, 'header_logistic_channel')"
                @changeItem="changeChannelItem($event, 'header_channel_id')"
              ></SelectChannel>
              <el-button
                type="primary"
                @click="handleTrialProfit(form.header_logistic_channel_id, 'head')"
                >运费试算</el-button
              >
              <el-input
                v-model="form.header_time"
                style="width: 100px"
                placeholder="时效（天）"
              ></el-input>
              <el-input
                style="margin-left: -1px"
                v-model.trim="form.header_freight"
                placeholder="预估运费"
                class="flex input-select flex-1 radius-left-0"
                oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,4}).*/,'$1')"
              >
                <template #append>
                  <el-button type="primary" class="suffix-unit">CNY</el-button>
                </template>
              </el-input>
              <el-button type="primary" @click="handleRecommendationChannel('head')"
                >推荐渠道</el-button
              >
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="尾程推荐渠道">
            <div class="flex w-full">
              <el-select
                class="!w-[140px] radius-right-0"
                v-model="form.tail_shipping_type_id"
                clearable
                placeholder="请选择运输方式"
                @change="changeTail"
              >
                <el-option
                  v-for="item in channel_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <SelectChannel
                v-model="form.tail_logistic_channel_id"
                placeholder="请选择物流渠道"
                type="tail"
                :transportType="form.tail_shipping_type_id"
                @change="changeChannel($event, 'tail_logistic_channel')"
                @changeItem="changeChannelItem($event, 'tail_shipping_type_id')"
              ></SelectChannel>
              <el-button
                type="primary"
                @click="handleTrialProfit(form.tail_logistic_channel_id, 'tail')"
                >运费试算</el-button
              >
              <el-input
                v-model="form.tail_time"
                style="width: 100px"
                placeholder="时效（天）"
              ></el-input>
              <el-input
                style="margin-left: -1px"
                v-model.trim="form.tail_freight"
                placeholder="预估运费"
                class="flex input-select flex-1 radius-left-0"
                oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,4}).*/,'$1')"
              >
                <template #append>
                  <el-button type="primary" class="suffix-unit">CNY</el-button>
                </template>
              </el-input>
              <el-button type="primary" @click="handleRecommendationChannel('tail')"
                >推荐渠道</el-button
              >
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="运营人员">
            <select-personnel
              class="w-full"
              v-model="form.operation_user_ids"
              :multiple="true"
              placeholder="请选择运营人员"
              @changeName="changeName"
            ></select-personnel>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否默认">
            <el-radio-group v-model="form.is_default">
              <el-radio :label="1" size="large">是</el-radio>
              <el-radio :label="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预估产品等级">
            <el-select class="w-full" v-model="form.estimated_product_level" clearable>
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].productLevelText"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目的仓">
            <SelectOverseasWarehouse
              class="w-full"
              v-model="form.destination_warehouse_id"
              placeholder="请选择目的仓"
            ></SelectOverseasWarehouse>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="flex justify-center py-2">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </div>
    </template>
  </el-dialog>
  <RecommendationLogistics
    ref="RecommendationLogisticsRef"
    @checked="checkedLogistics"
  ></RecommendationLogistics>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { reactive, toRefs } from "vue";
import SelectPlatformSite from "@/components/SelectPlatformSite";
import SelectCurrency from "@/components/SelectCurrency";
import { channel_options } from "@/utils/data.js";
import SelectChannel from "@/components/SelectChannel";
import RecommendationLogistics from "@/components/RecommendationLogistics";
import { feeTrialCalcFreight } from "@/api/index.js";
import SelectCountryCurrency from "@/components/Selects/SelectCountryCurrency";
import SelectOverseasWarehouse from "@/components/Selects/SelectOverseasWarehouse/index.vue";

import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();

const load = ref(false);
const visible = ref(false);

let options = reactive(inject("options"));

const emit = defineEmits(["close", "updateForm"]);
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
  listData: {
    type: Array,
    default: () => {
      return [];
    },
  },
  info: {
    type: Object,
    default: () => {
      return "";
    },
  },
});

const { listData, info } = toRefs(props);

const statusMap = new Map([
  ["add", "新增推荐平台/站点"],
  ["edit", "编辑推荐平台/站点"],
]);

const title = ref("");
// 打开弹窗
const open = async (type, row) => {
  title.value = statusMap.get(type);
  if (!load.value) {
    load.value = true;
    await 1;
  }
  if (row) {
    form.value = Object.assign({}, row);
  } else {
    initForm();
  }
  visible.value = true;
};

let form = ref({});

const initForm = () => {
  form.value = getForm();
};
// 初始化
const getForm = () => {
  return {
    platform_id: "", // 平台id
    platform_name: "", // 平台名称
    site_code: "", // 站点
    sales_price: "", // 售价
    currency_id: 158, // 币种id
    currency_name: "USD", // 币种
    header_channel_id: "", // 头程渠道id
    header_channel_name: "", //  头程渠道
    competitor_link: "", //  竞品链接
    is_default: 1,
  };
};
// 关闭弹窗
const close = () => {
  visible.value = false;
};

const handleClose = () => {
  initForm();
  emit("close");
};
// 提交
const save = () => {
  const newForm = Object.assign({}, form.value);

  if (!form.value.platform_id) {
    ElMessage.error("请选择平台");
    return;
  }
  if (!form.value.site_code) {
    ElMessage.error("请选择站点");
    return;
  }

  if (!form.value.site_country_code) {
    ElMessage.error("请选择国家");
    return;
  }
  listData.value.forEach((i) => {
    i.is_default = newForm.is_default == 1 && 2;
  });

  let find = listData.value.find(
    (i) =>
      i.platform_id == newForm.platform_id &&
      i.site_code == newForm.site_code &&
      i.id != newForm.id &&
      !i.delete
  );
  if (find) {
    ElMessage.error(`平台：${find.platform_name}，站点：${find.site_code}已存在`);
    return;
  }

  emit("updateForm", newForm);
  close();
};

const changePlatform = (val, index) => {
  form.value.platform_name = val;
};

const countryCurrencyRef = ref();
const changeSite = (val, index) => {
  form.value.site_name = val.site_name;
  // if (val.currency_name) {
  //   form.value.currency_id = item.currency_id;
  // } else {
  //   const find = countryOptions.value.find((i) => i.country == item.site_country_code);
  //   if (find) {
  //     form.value.currency_id = find?.base_currencys?.id;
  //   }
  // }

  form.value.site_country_code = val.site_country_code;
  countryCurrencyRef.value.change(val.site_country_code);
};

const changeHead = (val) => {
  const item = channel_options.find((i) => i.value == val);
  if (item != undefined) {
    form.value.header_channel_name = item.label;
  }
  form.value.header_logistic_channel_id = "";
  form.value.header_logistic_channel = "";
};

const changeTail = (val) => {
  const item = channel_options.find((i) => i.value == val);
  if (item != undefined) {
    form.value.tail_shipping_type = item?.label;
  }
  form.value.tail_logistic_channel_id = "";
  form.value.tail_logistic_channel = "";
};

const changeCurrency = (val) => {
  form.value.currency_name = val;
};

const changeName = (val) => {
  form.value.operation_user_ids_text = val;
};

defineExpose({ open });

// 选择物流渠道名称赋值
const changeChannel = (name, key) => {
  form.value[key] = name;
};

// 推荐渠道
const RecommendationLogisticsRef = ref();
const handleRecommendationChannel = (checked_type) => {
  if (
    !info.value.packing_size_cm?.width ||
    !info.value.packing_size_cm?.height ||
    !info.value.packing_size_cm?.length
  ) {
    ElMessage.error("请输入包装尺寸长、宽、高");
    return;
  }
  if (!form.value.platform_id) {
    ElMessage.error("请选择平台");
    return;
  }
  if (!form.value.site_code) {
    ElMessage.error("请选择站点");
    return;
  }

  const zip_code = form.value.site_code == "US" ? "63001" : "";

  const data = {
    sku_quantity: 1,
    width: info.value.packing_size_cm.width,
    length: info.value.packing_size_cm.length,
    height: info.value.packing_size_cm.height,
    delivery_mode: checked_type == "head" ? [2] : [1, 3],
    platform_id: form.value.platform_id,
    destination_country: form.value.site_country_code,
    zip_code,
    checked_type,
    package_weight: Number(info.value.package_weight / 1000),
    transport_type:
      checked_type == "head"
        ? form.value.header_channel_id
        : form.value.tail_shipping_type_id,
    freight_calc_mode: 3,
    warehouse: checked_type == "tail" ? form.value.destination_warehouse_id : null,
  };
  RecommendationLogisticsRef.value.open(data);
};

// 利润试算
const handleTrialProfit = async (val, checked_type) => {
  if (!val) return;
  if (
    !info.value.packing_size_cm?.width ||
    !info.value.packing_size_cm?.height ||
    !info.value.packing_size_cm?.length
  ) {
    ElMessage.error("请输入包装尺寸长、宽、高");
    return;
  }
  if (!form.value.platform_id) {
    ElMessage.error("请选择平台、站点");
    return;
  }
  if (!form.value.site_code) {
    ElMessage.error("请选择平台、站点");
    return;
  }
  if (!val) {
    ElMessage.error("请选择物流渠道");
    return;
  }
  const zip_code = form.value.site_code == "US" ? "63001" : "";

  const data = {
    sku_quantity: 1,
    width: info.value.packing_size_cm.width,
    length: info.value.packing_size_cm.length,
    height: info.value.packing_size_cm.height,
    delivery_mode: checked_type == "head" ? [2] : [1, 3],
    platform_id: form.value.platform_id,
    destination_country: form.value.site_country_code,
    zip_code,
    checked_type,
    package_weight: Number(info.value.package_weight / 1000),
    channel_id: val,
  };

  try {
    const res = await feeTrialCalcFreight({
      ...data,
    });

    if (res.data.length == 0) {
      return ElMessage.error("暂无数据");
    }
    if (checked_type == "head") {
      form.value.header_channel_id = res.data[0].transport_type;
      form.value.header_channel_name = res.data[0].transport_type_text;
      form.value.header_time = res.data[0].time_limit;
      form.value.header_freight = res.data[0].freight_cny;
    } else if (checked_type == "tail") {
      form.value.tail_shipping_type_id = res.data[0].transport_type;
      form.value.tail_shipping_type = res.data[0].transport_type_text;
      form.value.tail_time = res.data[0].time_limit;
      form.value.tail_freight = res.data[0].freight_cny;
    }
  } catch (e) {
    throw Error(e);
  }
};

// 选择后回调
const checkedLogistics = (row) => {
  if (row.checked_type == "head") {
    form.value.header_channel_id = row.transport_type;
    form.value.header_channel_name = row.transport_type_text;
    form.value.header_time = row.time_limit;
    form.value.header_freight = row.freight_cny;
    form.value.header_logistic_channel_id = row.channel_id;
    form.value.header_logistic_channel = row.channel_name;
  } else if (row.checked_type == "tail") {
    form.value.tail_shipping_type_id = row.transport_type;
    form.value.tail_shipping_type = row.transport_type_text;
    form.value.tail_time = row.time_limit;
    form.value.tail_freight = row.freight_cny;
    form.value.tail_logistic_channel_id = row.channel_id;
    form.value.tail_logistic_channel = row.channel_name;
  }
};

const changeChannelItem = (item, key) => {
  form.value[key] = item?.transport_type;
};

const changeCountryCurrency = (item) => {
  console.log(item);
  if (item.currency_id) {
    form.value.currency_id = item.currency_id;
    form.value.currency_name = item.base_currencys?.currency;
  }
};

onMounted(() => {
  if (!commonStore.channelOptions) {
    commonStore.getChannelList();
  }
});
</script>
